﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Text;
using System.Net.Mail;
using System.Net;
using Common.Util;
using Common.Properties;

namespace Common.Mail
{
    /// <summary>
    /// Рассылка почты
    /// </summary>
    public class MailSender
    {
        /// <summary>
        /// Настройки по отсылке почты
        /// </summary>
        public readonly MailSenderSettings MailSettings;

        public MailSender(MailSenderSettings settings)
        {
            this.MailSettings = settings;
        }


        public MailSender()
        {
            this.MailSettings = new MailSenderSettings
            {
                FromAddress = Settings.Default.SmtpFromAddress,
                FromAddressName = Settings.Default.SmtpFromAddressName,
                SmtpHost = Settings.Default.SmtpHost,
                SmtpLogin = Settings.Default.SmtpLogin,
                SmtpPassword = Settings.Default.SmtpPassword,
                SmtpPort = Settings.Default.SmtpPort,
                EnableSSL = Settings.Default.SmtpEnableSSL,
                MailSignature = Settings.Default.MailSignature
            };
        }


        /// <summary>
        /// Отсылает почту по указанным адресам
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="toAddresses"></param>
        /// <param name="copyToAddresses"></param>
        /// <param name="blindCopyTo">Адреса, на которые будет посылаться скрытая копия</param>
        /// <param name="attachments"></param>
        public void SendMail(string subject, string body, 
                IEnumerable<MailAddress> toAddresses, IEnumerable<MailAddress> copyToAddresses, IEnumerable<MailAddress> blindCopyTo,
                IEnumerable<Attachment> attachments)
        {
            toAddresses = toAddresses ?? new MailAddress[0];
            copyToAddresses = copyToAddresses ?? new MailAddress[0];
            blindCopyTo = blindCopyTo ?? new MailAddress[0];
            attachments = attachments ?? new Attachment[0];

            //Бьем адресатов на группы
            foreach (var toAddressGroup in CollectionHelper.ToGroups(toAddresses, Settings.Default.MaxAddressesCount))
            {
                MailMessage msg = new MailMessage();
                msg.Subject = subject;
                msg.Body = body;
                msg.IsBodyHtml = true;

                if (!String.IsNullOrEmpty(MailSettings.MailSignature))
                {
                    msg.Body += String.Format("<br />-----<br />{0}", MailSettings.MailSignature);
                }

                msg.SubjectEncoding = Encoding.UTF8;
                msg.BodyEncoding = Encoding.UTF8;
                msg.From = new MailAddress(MailSettings.FromAddress, MailSettings.FromAddressName ?? MailSettings.FromAddress);
                foreach (var address in toAddressGroup)
                {
                    msg.To.Add(address);
                }
                foreach (var address in copyToAddresses)
                {
                    msg.CC.Add(address);
                }
                foreach (var address in blindCopyTo)
                {
                    msg.Bcc.Add(address);
                }
                foreach (var attach in attachments)
                {
                    msg.Attachments.Add(attach);
                }

                var smtpClient = new SmtpClient(MailSettings.SmtpHost, MailSettings.SmtpPort);
                smtpClient.Credentials = new NetworkCredential(MailSettings.SmtpLogin, MailSettings.SmtpPassword);

                if (MailSettings.EnableSSL)
                {
                    smtpClient.EnableSsl = true;
                    //Доверяем всем сертификатам
                    ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
                }
                
                //Посылаем письмо, если есть кому посылать
                if (msg.To.Count > 0 || msg.CC.Count > 0)
                {
                    try
                    {
                        smtpClient.Send(msg);
                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                    

                }
            }
        }
    


    }
}
